/**
 * 配置管理服务
 * 用于动态管理系统配置，特别是authToken
 */
class ConfigService {
    constructor() {
        // 当前运行时的authToken配置（存储在内存中）
        this.runtimeAuthToken = null;

        // 默认的回退authToken配置
        this.defaultAuthToken = {
            "name": "13143359181",
            "expires": 1757322261597,
            "accessToken": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJ7XCJhY2NvdW50TnVtYmVyXCI6XCIxMzE0MzM1OTE4MVwiLFwiYWNjb3VudFR5cGVcIjowLFwiYXBwbHlTdGF0dXNcIjoyLFwiYnVzaW5lc3NUeXBlXCI6MixcImZyb21TeXN0ZW1cIjoxMyxcImlkXCI6NTQwMTUyLFwiaXNFeHBpcmVcIjpmYWxzZSxcImp3dElkXCI6XCI5NDRjMmM2NTdhNTQ0ODJkOWRkMzRkM2Q3YmI2ZDc4OFwiLFwibG9naW5OYW1lXCI6XCIxMzE0MzM1OTE4MVwiLFwibWVyY2hhbnRJZFwiOjUzMTU0OCxcInByb2ZpbGVcIjpcImdjcF91c193ZXN0MVwiLFwic3lzdGVtSWRcIjo4LFwidG9rZW5FeHBpcmVEYXRlXCI6MTc1NzMyMjI2MTQwNyxcIndlY2hhdFN1YlwiOmZhbHNlfSIsImlzcyI6Inp6LXNhYXMtcGVyaW1zc2lvbiIsImlhdCI6MTc1NjcxNzQ2MSwianRpIjoiOTQ0YzJjNjU3YTU0NDgyZDlkZDM0ZDNkN2JiNmQ3ODgifQ.AGhNKdNQfUi7FoxHBgiL33157ls6y8zUfmk-G585rX8",
            "userId": 540152,
            "phone": "13143359181",
            "locale": "en"
        };

        console.log('🔧 ConfigService初始化完成');
    }

    /**
     * 验证authToken格式
     */
    validateAuthToken(authToken) {
        if (!authToken || typeof authToken !== 'object') {
            return { valid: false, error: 'authToken必须是一个对象' };
        }

        const requiredFields = ['name', 'expires', 'accessToken', 'userId'];
        for (const field of requiredFields) {
            if (!authToken[field]) {
                return { valid: false, error: `authToken缺少必要字段: ${field}` };
            }
        }

        // 检查expires是否为有效数字
        if (typeof authToken.expires !== 'number' || authToken.expires <= 0) {
            return { valid: false, error: 'expires字段必须是有效的时间戳' };
        }

        // 检查token是否过期
        if (Date.now() > authToken.expires) {
            return { valid: false, error: 'authToken已过期' };
        }

        return { valid: true };
    }

    /**
     * 设置运行时authToken
     */
    setRuntimeAuthToken(newToken) {
        const validation = this.validateAuthToken(newToken);
        if (!validation.valid) {
            return {
                success: false,
                message: `authToken验证失败: ${validation.error}`
            };
        }

        this.runtimeAuthToken = { ...newToken };
        console.log('✅ 运行时authToken已更新');
        console.log(`- 用户: ${newToken.name}`);
        console.log(`- 用户ID: ${newToken.userId}`);
        console.log(`- 过期时间: ${new Date(newToken.expires).toLocaleString()}`);

        return {
            success: true,
            message: '运行时authToken更新成功'
        };
    }

    /**
     * 获取当前有效的authToken
     * 优先级：接口传入 > 运行时配置 > 默认配置
     */
    getEffectiveAuthToken(overrideToken = null) {
        // 1. 优先使用接口传入的token
        if (overrideToken) {
            const validation = this.validateAuthToken(overrideToken);
            if (validation.valid) {
                return overrideToken;
            }
        }

        // 2. 使用运行时设置的token
        if (this.runtimeAuthToken) {
            const validation = this.validateAuthToken(this.runtimeAuthToken);
            if (validation.valid) {
                return this.runtimeAuthToken;
            } else {
                console.warn('⚠️ 运行时authToken已过期，使用默认token');
                this.runtimeAuthToken = null; // 清除过期token
            }
        }

        // 3. 使用默认token
        return this.defaultAuthToken;
    }

    /**
     * 获取当前配置状态信息（隐藏敏感信息）
     */
    getConfigStatus() {
        const hasRuntimeToken = !!this.runtimeAuthToken;
        const runtimeTokenInfo = hasRuntimeToken ? {
            name: this.runtimeAuthToken.name,
            userId: this.runtimeAuthToken.userId,
            phone: this.runtimeAuthToken.phone,
            locale: this.runtimeAuthToken.locale,
            expires: this.runtimeAuthToken.expires,
            expiresDate: new Date(this.runtimeAuthToken.expires).toLocaleString(),
            isExpired: Date.now() > this.runtimeAuthToken.expires
        } : null;

        const defaultTokenInfo = {
            name: this.defaultAuthToken.name,
            userId: this.defaultAuthToken.userId,
            phone: this.defaultAuthToken.phone,
            locale: this.defaultAuthToken.locale,
            expires: this.defaultAuthToken.expires,
            expiresDate: new Date(this.defaultAuthToken.expires).toLocaleString(),
            isExpired: Date.now() > this.defaultAuthToken.expires
        };

        return {
            hasRuntimeToken,
            runtimeToken: runtimeTokenInfo,
            defaultToken: defaultTokenInfo,
            currentEffectiveToken: hasRuntimeToken && !runtimeTokenInfo?.isExpired ? 'runtime' : 'default'
        };
    }

    /**
     * 清除运行时authToken
     */
    clearRuntimeAuthToken() {
        this.runtimeAuthToken = null;
        console.log('🗑️ 运行时authToken已清除');
        return {
            success: true,
            message: '运行时authToken已清除，将使用默认配置'
        };
    }

    /**
     * 检查token是否过期
     */
    isTokenExpired(token = null) {
        const effectiveToken = this.getEffectiveAuthToken(token);
        return Date.now() > effectiveToken.expires;
    }
}

// 创建单例实例
const configService = new ConfigService();

module.exports = configService;